package core

import (
	"context"
	"log"
	"sync"
	"time"
)

// BasePlugin 提供通用的缓存队列、协程管理、生命周期控制
type BasePlugin struct {
	name      string
	dataCh    chan []byte
	ctx       context.Context
	cancel    context.CancelFunc
	wg        sync.WaitGroup
	queueSize int
	started   bool
}

// NewBasePlugin 创建一个带默认参数的插件基类
func NewBasePlugin(name string, queueSize int) *BasePlugin {
	if queueSize <= 0 {
		queueSize = 1000
	}
	ctx, cancel := context.WithCancel(context.Background())
	return &BasePlugin{
		name:      name,
		dataCh:    make(chan []byte, queueSize),
		ctx:       ctx,
		cancel:    cancel,
		queueSize: queueSize,
	}
}

func (bp *BasePlugin) Name() string { return bp.name }

// Recv 用于外部注入数据（类似 C++ 的 recv）
func (bp *BasePlugin) Recv(data []byte) bool {
	select {
	case bp.dataCh <- data:
		return true
	default:
		log.Printf("[%s] queue full, drop data", bp.name)
		return false
	}
}

// Start 启动后台处理线程
func (bp *BasePlugin) Start(handler func([]byte)) error {
	if bp.started {
		return nil
	}
	bp.started = true
	bp.wg.Add(1)
	go func() {
		defer bp.wg.Done()
		for {
			select {
			case <-bp.ctx.Done():
				return
			case data := <-bp.dataCh:
				handler(data) // 调用子类处理逻辑
			}
		}
	}()
	return nil
}

// Stop 优雅停止
func (bp *BasePlugin) Stop() error {
	if !bp.started {
		return nil
	}
	bp.cancel()
	done := make(chan struct{})
	go func() {
		bp.wg.Wait()
		close(done)
	}()
	select {
	case <-done:
	case <-time.After(2 * time.Second):
		log.Printf("[%s] stop timeout", bp.name)
	}
	bp.started = false
	return nil
}
